package com.ethan.auth.extention;

import com.ethan.enums.Constant;
import com.ethan.service.impl.SysUserServiceImpl;
import com.ethan.util.CommonUtil;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.security.util.SecurityConstants;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * @Description: TODO
 * @Author ethan
 * @CreateDate:2022/3/23 15:34
 * @UpdateDate: 2021/6/17 08:52
 * @Version 1.0
 */
@Data
public class PreAuthenticatedUserDetailsService <T extends Authentication> implements AuthenticationUserDetailsService<T>, InitializingBean {


    private Map<String, UserDetailsService> userDetailsServiceMap;
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.userDetailsServiceMap, "UserDetailsService must be set");
    }
    public PreAuthenticatedUserDetailsService(Map<String, UserDetailsService> userDetailsServiceMap) {
        Assert.notNull(userDetailsServiceMap, "userDetailsService cannot be null.");
        this.userDetailsServiceMap = userDetailsServiceMap;

    }
    @Override
    public UserDetails loadUserDetails(T token) throws UsernameNotFoundException {
        String clientId = CommonUtil.getOAuth2ClientId();
        if (clientId.equals(Constant.ADMIN)){
            UserDetailServceImpl service = (UserDetailServceImpl) userDetailsServiceMap.get(clientId);
            return service.loadUserByUsername(token.getName());
        }
        return null;
    }
}
